package accountManagementNew.interceptor;

import accountManagementNew.common.base.SpecialField;
import accountManagementNew.utils.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author：lihonbin
 * @Version：1.0.0
 * @Date:2025/9/24
 * @Description: 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在请求处理前进行调用
        // 1.获取当前请求的URI
        String url = request.getRequestURI();
        // 2.判断当前请求的URI是否为登录请求
        if (url.contains(SpecialField.LOGIN_URL)) { // 放行登录请求
            return true;
        }
        // 3.判断是否登录
        String token = request.getHeader(SpecialField.TOKEN);
        if (!StringUtils.hasLength(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 4.解析token
        if (!JWTUtil.validateToken(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 5.放行
        return true;
    }
}
